package lc.com.lcpicturebackend.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lc.com.lcpicturebackend.constant.CommonConstant;
import lc.com.lcpicturebackend.constant.EmailConstant;
import lc.com.lcpicturebackend.enums.UserRoleEnum;
import lc.com.lcpicturebackend.enums.VerificationCodeType;
import lc.com.lcpicturebackend.exception.BusinessException;
import lc.com.lcpicturebackend.exception.ErrorCode;
import lc.com.lcpicturebackend.exception.ThrowUtils;
import lc.com.lcpicturebackend.manager.auth.StpKit;
import lc.com.lcpicturebackend.manager.upload.FilePictureUpload;
import lc.com.lcpicturebackend.mapper.UserMapper;
import lc.com.lcpicturebackend.model.dto.flie.UploadPictureResult;
import lc.com.lcpicturebackend.model.dto.user.UserEditRequest;
import lc.com.lcpicturebackend.model.dto.user.UserLoginRequest;
import lc.com.lcpicturebackend.model.dto.user.UserQueryRequest;
import lc.com.lcpicturebackend.model.dto.user.UserRegisterRequest;
import lc.com.lcpicturebackend.model.entity.User;
import lc.com.lcpicturebackend.model.vo.LoginUserVO;
import lc.com.lcpicturebackend.model.vo.UserVO;
import lc.com.lcpicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static lc.com.lcpicturebackend.constant.UserConstant.*;

/**
 * @author 罗超
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2024-12-14 22:14:52
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private MailSender mailSender;

    @Resource
    private SimpleMailMessage templateMessage;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        // 1.校验参数
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR, "用户注册信息不能为空");
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String code = userRegisterRequest.getCode();

        ThrowUtils.throwIf(CharSequenceUtil.hasBlank(userAccount, code, userPassword, checkPassword)
                , ErrorCode.PARAMS_ERROR, "参数不能为空");
        String emailCodeKey = validateCode(userAccount, code, VerificationCodeType.REGISTER);

        // 密码和确定密码长度不能小于8位
        ThrowUtils.throwIf(userPassword.length() < 8 || checkPassword.length() < 8,
                ErrorCode.PARAMS_ERROR, "用户密码过短！");

        // 密码复杂度不能过低，必须包含字母、数字、特殊符号（正则校验）
        Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
        Matcher matcher = pattern.matcher(userPassword);
        ThrowUtils.throwIf(!matcher.matches(),
                ErrorCode.PARAMS_ERROR, "用户密码复杂度过低！");
        // 密码和确定密码是否相同
        ThrowUtils.throwIf(!userPassword.equals(checkPassword),
                ErrorCode.PARAMS_ERROR, "两次密码不一致！");

        // 2.查询用户是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long result = this.baseMapper.selectCount(queryWrapper);
        ThrowUtils.throwIf(result != 0, ErrorCode.PARAMS_ERROR, "账户已存在！");
        // 3.对密码加密
        String encryptPassword = encryptPassword(userPassword);
        // 4.插入账户数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        // 账户名的第一个字母或者文字
        int index = userAccount.indexOf('@');
        user.setUserName(userAccount.substring(0, index));
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        // 判断是否插入成功
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "用户注册失败！");
        // 删除缓存验证码
        stringRedisTemplate.delete(emailCodeKey);
        // 5.返回用户id
        return user.getId();
    }


    @Override
    public void sendCode(String email, VerificationCodeType type) {
        // 参数校验
        if (!StringUtils.hasText(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱不能为空");
        }
        boolean validEmail = this.isValidEmail(email);
        if (!validEmail) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        }
        String code = RandomUtil.randomNumbers(6);
        // 验证码存储、频率限制、过期时间
        extracted(email, type, code);
        // 发送邮件
        sendEmail(email, code);
    }


    @Override
    public void getCaptcha(String captchaId, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 创建线段干扰的验证码，宽度160，高度40，4位验证码，干扰线数40
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(160, 40, 4, 40);

            // 将验证码存入redis中
            String emailCodeKey = String.format(EmailConstant.EMAIL_VERIFY_CODE, "LOGIN", captchaId);
            stringRedisTemplate.opsForValue().set(emailCodeKey, lineCaptcha.getCode(), 1, TimeUnit.MINUTES);
            // 设置响应类型为图片
            response.setContentType("image/png");
            // 输出图片流
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "生成验证码失败,请联系管理员！");
        }
    }


    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求类
     * @param request          http请求
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        String code = userLoginRequest.getCode();
        String captchaId = userLoginRequest.getCaptchaId();
        // 1. 校验
        if (CharSequenceUtil.hasBlank(userAccount, userPassword, code,captchaId )) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4 || userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱或者密码格式错误");
        }
        // 验证码校验
        String emailCodeKey = this.validateCode(captchaId, code, VerificationCodeType.LOGIN);
        // 2. 加密
        String encryptPassword = encryptPassword(userPassword);
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        // 4.将用户登录态保存到Sa-token中,便于在空间鉴权时使用
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);
        // 删除缓存验证码
        stringRedisTemplate.delete(emailCodeKey);
        return this.getLoginUserVO(user);
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }


    /**
     * 用户信息脱敏
     *
     * @param user 用户信息
     * @return 脱敏后的用户信息
     */
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        // 脱敏
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserListVO(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public boolean isValidEmail(String email) {
        // 获取EmailValidator实例
        EmailValidator validator = EmailValidator.getInstance();
        // 验证邮箱
        return validator.isValid(email);
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String searchSpaceUser = userQueryRequest.getSearchSpaceUser();
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 从数据库中多字段中搜索
        if (!CharSequenceUtil.isBlank(searchSpaceUser)) {
            queryWrapper.and(
                    qw -> qw.like("id", searchSpaceUser)
                            .or()
                            .like("userAccount", searchSpaceUser)
            );
        }
        queryWrapper.eq(ObjectUtil.isNotNull(id), "id", id);
        queryWrapper.eq(CharSequenceUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(CharSequenceUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(CharSequenceUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(CharSequenceUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(CharSequenceUtil.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    /**
     * 密码加密
     *
     * @param userPassword 密码
     * @return 加密后的密码
     */
    @Override
    public String encryptPassword(String userPassword) {
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    @Override
    public void editUser(UserEditRequest userEditRequest, Object multipartFile, User loginUser) {
        if (userEditRequest.getUserProfile().length() > 255) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户简介长度255个字符");
        }
        String uploadPathPrefix = String.format("private/%s/avatar", loginUser.getId());
        UploadPictureResult uploadPictureResult = filePictureUpload.uploadPicture(multipartFile, uploadPathPrefix);
        String avatarUrl = uploadPictureResult.getUrl();
        User user = new User();
        user.setId(userEditRequest.getId());
        user.setUserName(userEditRequest.getUserName());
        user.setUserAvatar(avatarUrl);
        user.setUserProfile(userEditRequest.getUserProfile());
        // 当前编辑时间
        user.setEditTime(new Date());
        boolean result = this.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 发送邮件
     *
     * @param email 邮箱
     * @param code  验证码
     */
    private void sendEmail(String email, String code) {
        try {
            SimpleMailMessage msg = new SimpleMailMessage(templateMessage);
            msg.setTo(email);
            msg.setText(String.format("您的验证码是：%s\n" +
                            "有效期5分钟，请勿泄露给他人。"
                    , code));
            this.mailSender.send(msg);

            log.info("验证码发送成功，邮箱：{}，验证码：{}", email, code);
        } catch (MailSendException e) {
            log.error("邮件发送失败，邮箱：{}", email, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "邮件发送失败，请检查邮箱地址");
        } catch (MailException e) {
            log.error("邮件服务异常", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "邮件服务暂时不可用");
        }
    }


    /**
     * 校验验证码是否正确
     *
     * @param captchaId 验证码id
     * @param code      验证码
     * @param type      操作类型
     * @return key
     */
    private String validateCode(String captchaId, String code, VerificationCodeType type) {
        // 从缓存中获取验证码
        String emailCodeKey = String.format(EmailConstant.EMAIL_VERIFY_CODE, type.getCode(), captchaId);
        String cacheCode = stringRedisTemplate.opsForValue().get(emailCodeKey);
        if (StrUtil.isBlank(cacheCode) || !cacheCode.equals(code)) {
            if (type.getCode().equals("LOGIN")) {
                stringRedisTemplate.delete(emailCodeKey);
            }
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误");
        }
        return emailCodeKey;
    }

    /**
     * 验证码存储、频率限制、过期时间
     *
     * @param email 邮箱
     * @param type  验证码类型("登录"或"注册")
     * @param code  验证码
     */
    private void extracted(String email, VerificationCodeType type, String code) {
        String freyKey = String.format(EmailConstant.EMAIL_VERIFY_FREQ, type.getCode(), email);
        String codeKey = String.format(EmailConstant.EMAIL_VERIFY_CODE, type.getCode(), email);
        // 判断邮箱是否频繁发送
        if (stringRedisTemplate.hasKey(freyKey)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码不正确");
        }

        // 缓存验证码,设置5min过期时间
        stringRedisTemplate.opsForValue().set(
                codeKey,
                code,
                EmailConstant.EMAIL_VERIFY_EXPIRE,
                TimeUnit.MINUTES);
        // 设置频率锁（安全防护）
        stringRedisTemplate.opsForValue().set(
                EmailConstant.EMAIL_VERIFY_FREQ + email,
                "lock",
                EmailConstant.EMAIL_VERIFY_FREQ_LIMIT,
                TimeUnit.MINUTES);
    }

}




